

#include "GenCrack.h"
#include <time.h>
#include <iostream>



class MyGenerator : public TCombinatorio {
	private:
		FILE	*out;
		time_t	start, end;		
		char	tmpChar[3];
		//
		// gestione elaborazione distribuita:
		unsigned long		count;

	public:
		MyGenerator(unsigned char *num, unsigned short num_comb) : TCombinatorio(num, num_comb, true)
		{
			out = NULL;
		}

		void callback_accept_voluntary(const TSocketInfo *voluntary) {
			printf("\nAggiunto nuovo slave %s:%d accettata.", voluntary->ip, voluntary->port);
		}

		void callback_send_work_unit(const TSocketInfo *slave, const unsigned char *combinazione, unsigned short len_array) {
			printf("\nUnita' [%s] inviata allo slave %s:%d", combinazione, slave->ip, slave->port);
		}

		void callback_work_unit_complete(const TSocketInfo *slave, __int64 total) {
			printf("\nNotifica unita' lavorativa completata per lo slave: %s:%d [totale: %lu]", slave->ip, slave->port, total);
		}
		//
		// callback ridefinite:		
		void callback_new_combination(const_lista combinazione, unsigned short len_array) {
			this->LockForCallback();
			fprintf(this->out, "%s\n", combinazione->Number);
			count++;
			this->UnlockForCallback();
		}

		// ----- CLEANER CALLBACK -----
		void callback_start_cleaner(void) 
		{
			printf("\nPulizia memoria...");
		}

		void callback_end_cleaner(void) 
		{
			printf("COMPLETATA\n");
		}

		// ----- BRUTE FORCE CALLBACK -----
		void callback_start_generate_bruteforce(void) {
			out = fopen("out.txt", "w");
			time(&start);			
			count = 0;
			printf("\nInizio brute force in grid computing\n");			
		}

		void callback_end_generate_bruteforce(void) {
			fclose(this->out);
			time(&end);
			printf("\nElaborazione distribuita completata\n\nTempo trascrorso: %.2fs\nTotali elaborate: %d\n", difftime(end, start), count);
		}

		void callback_partial_generate_bruteforce(const char *word) 
		{
			printf("\nInvio nuova unita' di elaborazione [ %s ]", word);
		}		
};



int main(void)
{
	unsigned char	perms[] = "fake";
	char			*prefix = ".", *postfix = "-";	
	MyGenerator		comb(perms, 2);
	bool			ret = false;

	ret = comb.MasterListen("192.198.3.15", 54321);
	if (ret == false) {
		printf("\nError: %s", comb.GetLastErrorString());
		getchar();
		exit(EXIT_FAILURE);
	}
	printf("\nServer master in ascolto...\nEnter per avviare elaborazione distribuita:");
	getchar();		
	if (comb.GenerateFastBruteForce((const unsigned char *)prefix, 0, 0, (const unsigned char *)postfix, 0, 0, "../../password", 2) == false)
		fprintf(stderr, "%s", comb.GetLastErrorString());
	else
		printf("\nServer master in listen: enter per terminare");	
	getchar();
	comb.MasterAbortRequest();
	//comb.CloseMasterListner();
	return (0);
}
